package com.cloudwise.thread;

/**
 * @author ：Teacher陈
 * @date ：Created in 2021/1/6 16:20
 * @description：死锁
 * @modified By：
 * @version: 1
 */
public class DeadLock implements Runnable {
    private static final Father father = new Father();
    private  static  final Child child = new Child();

    //设置开关
    private boolean flag = false;


    @Override
    public void run() {
        if (flag) {
            //父亲运行
            synchronized (father) {
                father.say();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (child) {
                    father.get();
                }
            }
        } else {
            //孩子运行
            synchronized (child) {
                child.say();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (father) {
                    child.get();
                }
            }

        }
    }


    public static void main(String[] args) {
        DeadLock deadLock1 = new DeadLock();
        DeadLock deadLock2 = new DeadLock();
        deadLock1.flag = true;
        deadLock2.flag = false;
        new Thread(deadLock1).start();
        new Thread(deadLock2).start();

    }
}
